import { _decorator, Button, Label, labelAssembler, Node, ProgressBar, ScrollView, tween, UIOpacity, v3 } from 'cc';
import { ScrollList } from '../../../A-FRAME/component/scroll.list';
import { BasePopUp } from '../../../A-FRAME/component/ui.pop-up';
import { Popup } from '../page/popup';
import GlobalData from '../../../game/GlobalData';
import { MainGameLogic } from '../../../game/MainGameLogic';
import LocalizedLabel from '../../../i18n/LocalizedLabel';
import ServiceAPI from '../../api/service.api';
import { ClientAPI } from '../../api/client.api';
import { AudioManager } from '../../../AudioManager';
import { Url } from '../../../Url';
import { NCPoint } from '../../api/api.config.client';
const { ccclass, property } = _decorator;

@ccclass('MissionPage')
export class MissionPage extends BasePopUp<typeof Popup, null> {
    protected default_return: null;
    @property(ScrollList)
    private scroll_list: ScrollList = null;
    @property(ScrollView)
    private scroll_view: ScrollView = null;


    @property(Node)
    mission: Node = null;
    @property(Node)
    missionward: Node = null;
    @property(Node)
    lessBtn: Node = null;

    taskId: number = 0;
    cashReward: number = 0;

    @property(Node)
    shan: Node = null;

    protected initAfterOnLoad(): void {
        this.scroll_list.onRenderItem(this.renderItem.bind(this));
    }

    public async onShow(list: DATA[]) {
        BasePopUp.jelly_enter(this.node);
        this.renderLocalUI();
        this.scroll_list.setDataList(list, 'taskId');
        this.scroll_view.scrollToTop(0.05);
    }

    protected _click_event_: { [name: string]: (this: MissionPage, button: Button) => void; } = {
        closeBtn(btn) {
            AudioManager.ins.playOneShot(Url.AUDIO.SFX4, 1);
            btn.interactable = false;
            BasePopUp.jelly_leave(this.node).then(() => {
                btn.interactable = true;
                this.close(null);
            });
        },
        async douBtn(btn) {
            AudioManager.ins.playOneShot(Url.AUDIO.SFX4, 1);
            // 广告请求是否成功
            let isCom = await ClientAPI.AD("incentive",'ad');
            if (isCom) {
                btn.interactable = false;
                let config = await ServiceAPI.MissionReport(GlobalData.userId, this.taskId, true);
                MainGameLogic.ins.updateMissionStatus(this.taskId, true)
                //  加钱逻辑
                MainGameLogic.ins.updateCashLabel(config.cashTotal);
                MainGameLogic.ins.shwoGetCashEffect(v3(0, 0, 0));
            }
            BasePopUp.jelly_leave(this.node).then(() => {
                btn.interactable = true;
                this.close(null);
            });
        },
        async lessBtn(btn) {
            btn.interactable = false;
            AudioManager.ins.playOneShot(Url.AUDIO.SFX4, 1);
            let config = await ServiceAPI.MissionReport(GlobalData.userId, this.taskId, false);
            MainGameLogic.ins.updateMissionStatus(this.taskId, true)
            //  加钱逻辑
            MainGameLogic.ins.updateCashLabel(config.cashTotal);
            MainGameLogic.ins.shwoGetCashEffect(v3(0, 0, 0));
            BasePopUp.jelly_leave(this.node).then(() => {
                btn.interactable = true;
                this.close(null);
            });
        }
    }

    private renderItem(item: Node, data: DATA, cache_map: Map<Node, ItemCache>) {
        let cache = cache_map.get(item);
        if (!cache) {
            cache = this.createCache(item);
            cache_map.set(item, cache);
        }

        cache.lbl_cash.string = MainGameLogic.ins.formatCashValue(data.cashReward);
        cache.bar.progress = GlobalData.elimiTimes / data.eliminateCount;
        cache.lbl_desc.setTextKeyAndOption("pop_missionpage_miscond_text", data.eliminateCount);

        cache.claimBtn.on(Node.EventType.TOUCH_START, this.claimBtnCallBack.bind(this, data));
        if (data.isComplete && !data.isGetReward) {
            cache.claimBtn.active = true;
            cache.lbl_pro.string = data.eliminateCount + '/' + data.eliminateCount;
        } else if (data.isComplete && data.isGetReward) {
            cache.claimBtn.active = true;
            cache.lbl_pro.string = data.eliminateCount + '/' + data.eliminateCount;
            cache.claimBtn.getChildByName('button_m').active = false;
            // cache.lbl_state.setTextKeyAndOption("pop_missionpage_misstate_text1");
        } else {
            cache.claimBtn.active = false;
            cache.lbl_pro.string = GlobalData.elimiTimes + '/' + data.eliminateCount;
            // cache.lbl_state.setTextKeyAndOption("pop_missionpage_misstate_text");
        }
    }

    claimBtnCallBack(data: DATA) {
        if (data.isGetReward) {
            // console.log('此任务奖励已领取');
            return
        }
        this.taskId = data.taskId;
        this.cashReward = data.cashReward
        ClientAPI.Point(NCPoint.TASKDONE, { userid: GlobalData.userId });
        BasePopUp.jelly_leave(this.mission).then(() => {
            this.mission.active = false;
            this.missionward.active = true;
            BasePopUp.jelly_enter(this.missionward);
        })
        tween(this.shan)
            .by(6, { angle: 360 })
            .repeatForever()
            .start()
        this.missionward.getChildByName('Label').getComponent(Label).string = '+' + MainGameLogic.ins.formatCashValue(data.cashReward);

    }

    private createCache(node: Node): ItemCache {
        return {
            bar: node.getChildByName('ProgressBar').getComponent(ProgressBar),
            lbl_cash: node.getChildByName('lbl-cash').getComponent(Label),
            lbl_desc: node.getChildByName('lbl-desc').getComponent(LocalizedLabel),
            claimBtn: node.getChildByName('claimBtn'),
            lbl_pro: node.getChildByName('lbl_pro').getComponent(Label),
            lbl_state: node.getChildByName('pendingLabel').getComponent(LocalizedLabel)
        }
    }

    renderLocalUI() {
        this.mission.active = true;
        this.missionward.active = false;
    }
}

type DATA = {
    "taskId": number,
    "eliminateCount": number,
    "missionLevel": number,
    "isComplete": boolean,
    "isGetReward": boolean,
    "cashReward": number
}

type ItemCache = {
    lbl_cash: Label;
    bar: ProgressBar;
    lbl_desc: LocalizedLabel;
    claimBtn: Node;
    lbl_pro: Label;
    lbl_state: LocalizedLabel
}

